package com.algo.panelmn;
import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

public class CountIPtest extends Configured implements Tool {
	public static class Mapper extends org.apache.hadoop.mapreduce.Mapper<LongWritable, Text, Text, LongWritable> 
	{
		LongWritable one = new LongWritable(1);
		public void map(LongWritable key, Text value, Context context)
				throws IOException, InterruptedException {
			String str=value.toString();
			int beg=str.indexOf("^ip=");
			int end=str.indexOf("^",beg+4);
			String caid=str.substring(beg+4,end);
			context.write(new Text(caid), one);
		}
	}
	public static class Reducer extends org.apache.hadoop.mapreduce.Reducer<Text, LongWritable, Text, LongWritable> 
	{
		public void reduce(Text key, Iterable<LongWritable> values,Context context)
			 throws IOException, InterruptedException 
                {
			Long sum = 0L;
			for (LongWritable value : values) {
				sum += value.get();
			}
			context.write(key, new LongWritable(sum));
		}
	}
	public static void main(String[] args) throws Exception {
		int res = ToolRunner.run(new Configuration(), new CountIPtest(), args);
		System.exit(res);
	}

	public int run(String[] args) throws Exception {

		Configuration conf = getConf();
                conf.set("caidfilename","caid.txt");
		@SuppressWarnings("deprecation")
		Job job = new Job(conf, "test");
		job.setJarByClass(CountIPtest.class);
		job.setMapperClass(Mapper.class);
		job.setReducerClass(Reducer.class);
		job.setInputFormatClass(com.supertool.tong.merger.util.MzSequenceFileCaidInputFormat.class);
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(LongWritable.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(LongWritable.class);

		//job.setNumReduceTasks(0);

		FileOutputFormat.setOutputPath(job, new Path(args[1]));
		FileInputFormat.addInputPath(job, new Path(args[0]));

		return job.waitForCompletion(true) ? 0 : 1;
	}
}
